import React from 'react'
import { Form, Input,Spin,Select, Col,  Button, Modal, message,Breadcrumb } from 'antd'
//引入标准Fetch及IE兼容依赖
import 'whatwg-fetch';
const FormItem = Form.Item
import  config from '../../assets/config';
class studentForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            loading:false,
            startValue:null,
            addtwo:'fromItem active',
            btnText:"从学员档案录入"
        }
    }

    // 提交表单
    handleSubmit = (e) => {
        this.props.form.validateFields((errors, values) => {
            this.hideModal()
          if (!!errors) {
            console.log('Errors in form!!!');
            message.error('操作失败!');
            return;
              };
          values.courseId=this.props.location.state;
          this.postForm(values)
        });

        //this.props.form.resetFields()
    }
    postForm=(json)=>{
        this.setState({loading:true});
        fetch(config.base+"apply/add",{
                method: 'POST',
                mode: config.cors,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body:config.postBody(json)
        }).then(res=>{return res.json()})
        .then(rep=>{
            this.setState({loading:false});
            rep.status==200? message.success(rep.message): message.error(rep.message);
        })
        .catch((e)=>{console.log(e.message);message.error('网络错误，请稍后重试');this.setState({loading:false});})
    }

    // 显示弹框
    showModal = () => {
        this.setState({ visible: true })
    }


    // 隐藏弹框
    hideModal = () => {
        this.setState({ visible: false })
    }

    addsuccess=()=>{
    	message.success('操作成功!');
    	this.hideModal();
    }


    disabledEndDate=(end)=>{
        if (!end || !this.state.startValue) {
          return false;
        }
        return end.getTime() < this.state.startValue.getTime();
    }
    phoneCheck(rule, value, callback){
    	if (!value) {
	      callback();
	    } else {
	    	if(!(/^1[34578]\d{9}$/.test(value))){
	    		callback([new Error('请输入正确手机号')]);
	    	}else{
	    		callback();
	    	}
	    }
    }
    userExists=(rule, value, callback)=>{
	    if (!value) {
	      callback();
	    } else {
	    	if(value.length&&!(/^\d{15}(\d{2}[0-9xX])$/.test(value))){
		          callback([new Error('身份证号码不合法')]);
	    	}else {
	          fetch(config.base+"student/check",{
                method: 'POST',
                mode: config.cors,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body:'idCardNum='+value
		        }).then(res=>{return res.json()})
		        .then(rep=>{
		            if(rep.status==201){
                        this.setState({
                            addtwo:'fromItem active',
                            btnText:"从学员档案录入"
                        })
                        message.success('该学员在档案中，请直接录入')
                        callback()
                        }else{
                        this.setState({
                            addtwo:'fromItem disactive',
                            btnText:"单个学员录入"
                        })
                        message.success('该学员不在档案中，请重新录入')
                        callback()
                    };
		        })
		        .catch((e)=>{console.log(e.message);message.success('网络错误请重试');callback()})
	        }
	    }
	  }
      legitimateEmail(rule,value,callback){
        if(!value){
            callback();
        }else if(!/^\w*\@\w*\.\w*$/.test(value)){
            callback([new Error('请输入正确邮箱')]);
        }else{
            callback();
        }
      }
    render() {
        const { getFieldProps } = this.props.form
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 }
        }

        return (
        <Spin spinning={this.state.loading}>
        <Breadcrumb ><Breadcrumb.Item><a href="javascript:window.history.go(-1);">返回</a></Breadcrumb.Item></Breadcrumb>
            <Form horizontal onSubmit={this.handleSubmit} className="animated fadeInUp ">
                <FormItem
                    id="control-input2"
                    label="身份证号码"
                    {...formItemLayout}
                     hasFeedback>
                    <Input id="control-input2" placeholder="请输入身份证号码..."
                    {...getFieldProps('idCardNum', {
                      rules: [
                        { required: true,message: '请输入15-18位身份证号码' },
                        { validator: this.userExists }
                      ],

                    })} />
                </FormItem>
                <div className={this.state.addtwo}>
                <FormItem
                    id="control-input1"
                    label="真实姓名"
                    {...formItemLayout}
                     hasFeedback>
                    <Input id="control-input1" placeholder="请输入真实姓名..."
                    {...getFieldProps('realName')} />
                </FormItem>
                <FormItem
                    id="control-input3"
                    label="邮箱"
                    {...formItemLayout}
                     hasFeedback>
                    <Input id="control-input3" placeholder="请输入邮箱..."
                    {...getFieldProps('email',{
                        rules: [{validator:this.legitimateEmail}]
                    })}  />
                </FormItem>
                <FormItem
                    id="control-input4"
                    label="手机号码"
                    {...formItemLayout}
                     hasFeedback>
                    <Input id="control-input4" placeholder="请输入手机号码..."
                    {...getFieldProps('phone', {
                      rules: [
                        { required: false,message: '请输入手机号码' },
                        { validator: this.phoneCheck }
                      ],

                    })} />
                </FormItem>


                <FormItem
                    id="control-textarea"
                    label="住址"
                    {...formItemLayout} >
                    <Input type="textarea" id="control-textarea" rows="3"
                    {...getFieldProps('address')} />
                </FormItem>
                </div>
                <FormItem wrapperCol={{ span:12, offset:6 }} style={{ marginTop: 24 }}>
                    <Button  type="primary block" onClick={this.showModal}>{this.state.btnText}</Button>
                </FormItem>
                <Modal title="提示" visible={this.state.visible} loading={this.state.iconLoading}   onOk={this.handleSubmit} onCancel={this.hideModal}>
                    确定录入此学生吗？
                </Modal>
            </Form>
        </Spin>
        )
    }
}

studentForm = Form.create()(studentForm)

export default studentForm